package cn.school.workflow.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.school.common.utils.SysUserUtils;
import cn.school.workflow.dao.MaterialCollectDao;
import cn.school.workflow.service.MaterialCollectService;
import cn.school.workflow.vo.MaterialCollectVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

@Service
public class MaterialCollectServiceImpl extends ServiceImpl<MaterialCollectDao, MaterialCollectVO> implements MaterialCollectService {

    @Override
    public IPage<MaterialCollectVO> findMaterialCollectPageList(MaterialCollectVO vo) {
        LambdaQueryWrapper<MaterialCollectVO> wrapper = new LambdaQueryWrapper<>(vo);
        if(!StringUtils.isEmpty(vo.getCollectUser())){
            wrapper.like(MaterialCollectVO::getCollectUser,vo.getCollectUser());
        }
        if(!StringUtils.isEmpty(vo.getMaterialName())){
            wrapper.like(MaterialCollectVO::getMaterialName,vo.getMaterialName());
        }
        wrapper.orderByDesc(MaterialCollectVO::getCreateTime);
        return page(new Page<>(vo.getPageNum(), vo.getPageSize()), wrapper);
    }

    @Override
    public int addOrUpdateMaterialCollect(MaterialCollectVO vo) {
         String username = SysUserUtils.getSysUser().getUsername();
         int num=0;
         if(StringUtils.isEmpty(vo.getId())){
             vo.setCreateBy(username);
             vo.setCreateTime(new Date());
             num = this.baseMapper.insert(vo);
         }else{
             vo.setModifyTime(new Date());
             vo.setModifyBy(username);
             num = this.baseMapper.updateById(vo);
         }
        return num;
    }

    @Override
    public int deleteMaterialCollectById(Long id) {
        return this.baseMapper.deleteById(id);
    }

    @Override
    public int repayProcess(Long id) {
        MaterialCollectVO vo = this.baseMapper.selectById(id);
        if(!"1".equals(vo.getIsRepay())){
            //无须归还
            return -1;
        }
        vo.setRepayTime(DateUtil.formatDateTime(new Date()));
        return this.baseMapper.updateById(vo);
    }
}
